<?php
/**
 * @brief   公用类
 * @note    公用类
 * @author  huangfeng
 * @version 1.0
 * @since   2024-6-26
 */
namespace app\common;


use app\api\model\Operator;
use app\api\exception\ParameterException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Lang;
use think\Request;

class Common
{

    /**
     * 根据系统数据字典的value值返回显示的Text值
     * @author huangfeng
     * @date 2024-06-27
     * @param string $p_strLang:语言
     * @param string $p_strValue:逗号分隔的value值
     * @param string $p_strDictName:数据字典名称
     * @param string $p_strKey:返回字段名 默认 name
     * @param string $p_strDot:连接的分隔符 默认为逗号
     * @return 返回显示的Text值
     */
    public function getSysDictText($p_strLang,$p_strValue,$p_strDict,$p_strKey = 'name',$p_strDot = ',')
    {
        $strValue = '';
        if (!empty($p_strValue) && !empty($p_strDict) && !empty($p_strLang))
        {
            $DD_PATH = Config::get('app.datadict_path');
            if (file_exists($DD_PATH.'/'. $p_strLang . '/' . $p_strDict . '.php')){
                $arrDict = include $DD_PATH.'/'. $p_strLang . '/' . $p_strDict . '.php';
                if (is_array($arrDict)){
                    $arrValue = explode(",", $p_strValue);
                    for ($i=0;$i<count($arrValue);$i++){
                        if (isset($arrDict[$arrValue[$i]][$p_strKey])){
                            if (empty($strValue)){
                                $strValue = trim($arrDict[$arrValue[$i]][$p_strKey],$p_strDot);
                            }else{
                                $strValue .= $p_strDot.trim($arrDict[$arrValue[$i]][$p_strKey],$p_strDot);
                            }
                        }
                    }
                }
            }
        }
        return $strValue;
    }

    /**
     * 生成随机字符串
     * @author huangfeng
     * @date 2024-06-27
     * @param int $p_intLength:字符串长度
     * @return string
     */
    public function getRandomString($p_intLength = 8) {
        $characters = '0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHLJKMNPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $p_intLength; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }


    /**
     *  生成纯数字随机数
     */

    public static function getSerialNo($length)
    {
        static $seed = array(0,1,2,3,4,5,6,7,8,9);
        $str = '';
        for($i=0;$i<$length;$i++) {
            $rand = rand(0,count($seed)-1);
            $temp = $seed[$rand];
            $str .= $temp;
            unset($seed[$rand]);
            $seed = array_values($seed);
        }
        return $str;
    }

    /**
     * 订单生成
     * 订单字符 第一位 年份
     * 订单字符 第二位 月
     * 订单字符 第三位 日
     *  其余字母使用 销售缩写名字
     * @param int $sales_id :销售ID
     */

    public function generateOrderNo($sales_id = null, $length = 8) {

        $yearArr = ['2024' => 'A', '2025' => 'B', '2026' => 'C', '2027' => 'D', '2028' => 'E', '2029' => 'F', '2030' => 'G', '2031' => 'H', '2032' => 'I', '2033' => 'J'];
        $monthArr = ['01' => 'A', '02' => 'B', '03' => 'C', '04' => 'D', '05' => 'E', '06' => 'F', '07' => 'G', '08' => 'H', '09' => 'I', '10' => 'J', '11' => 'K', '12' => 'L'];
        $dayArr = ['01' => 'A', '02' => 'B', '03' => 'C', '04' => 'D', '05' => 'E', '06' => 'F', '07' => 'G', '08' => 'H', '09' => 'I', '10' => 'J', '11' => 'K', '12' => 'L', '13' => 'M', '14' => 'N', '15' => 'O', '16' => 'P', '17' => 'Q', '18' => 'R', '19' => 'S', '20' => 'T', '21' => 'U', '22' => 'V', '23' => 'W', '24' => 'X', '25' => 'Y','26' => 'Z', '27' => 'a', '28' => 'b', '29' => 'c', '30' => 'd', '31' => 'e'];

        /* 年 */
        $Year = $yearArr[date('Y')];

        /* 月 */
        $Month = $monthArr[date('m')];

        /* 日 */
        $Day = $dayArr[date('d')];

        /* 随机生成8位的流水号 */
        $SerialNo = $this->getSerialNo($length);

        /* 员工缩写 */
        if (is_null($sales_id)) {
            $sales_id = Config::get('operator.default_sales_id');
        }

        $Sales = Operator::where('id',$sales_id)->value('abbr') ?? "XM";

        if(!$Sales){
            throw new ParameterException([
                'message' => Lang::get('operator.noSalespersonFound')
            ]);
        }

        /* 订单号 */
        return $Year.$Month.$Day.$Sales.$SerialNo;
    }

    /**
     * 生成订单号
     * @param int $source 订单来源 1-国内 2-国外
     * @param int $ownerId 销售ID（操作员ID）
     * @param string|null $createTime 订单创建时间（可选）
     * @return string 生成的订单号
     * @throws \think\db\exception\DbException
     */
    function generateOrderNoNew(int $source, int $ownerId, ?string $createTime = null): string
    {
        // 1. 确定地区前缀 HK/CN
        $prefix =  $source == 2 ? 'HK' : 'CN';

        // 2. 获取销售缩写
        if ($ownerId > 0) {
            $operator = Db::name('operator')->where('id', $ownerId)->find();
            $abbr = $operator['abbr'] ?? '';

            // 处理缩写格式：取前两位大写，不足两位用O补齐
            $abbrCode = !empty($abbr)
                ? strtoupper(substr($abbr, 0, 2))
                : 'OF';
            $abbrCode = str_pad($abbrCode, 2, 'O', STR_PAD_RIGHT);
        } else {
            $abbrCode = 'OF';
        }

        // 3. 处理创建日期 (yyMMdd)
        $date = $createTime ?: date('Y-m-d H:i:s');
        $dateCode = date('ymd', strtotime($date));

        // 4. 获取当天订单序号 (事务内加锁确保唯一)
        $startTime = date('Y-m-d 00:00:00', strtotime($date));
        $endTime = date('Y-m-d 23:59:59', strtotime($date));


            $orderCount = Db::name('order')
                ->where('owner', $ownerId)
                ->where('create_time', '>=', $startTime)
                ->where('create_time', '<=', $endTime)
                ->count();
            if($abbrCode == 'OF'){
                $orderCount = Db::name('order')
                    ->whereLike('order_no', "%{$abbrCode}{$dateCode}%")
                    ->where('create_time', '>=', $startTime)
                    ->where('create_time', '<=', $endTime)
                    ->count();
            }

            $sequence = $orderCount + 1;

        // 序号格式化为两位数字
        $sequenceCode = str_pad($sequence, 2, '0', STR_PAD_LEFT);

        // 5. 拼接最终订单号
        return "{$prefix}{$abbrCode}{$dateCode}{$sequenceCode}";
    }
    function generateOrderNoZc( int $ownerId, ?string $createTime = null): string
    {
        // 1. 确定地区前缀 HK/CN
        $prefix =  'ZC';

        // 2. 获取销售缩写
        if ($ownerId > 0) {
            $operator = Db::name('operator')->where('id', $ownerId)->find();
            $abbr = $operator['abbr'] ?? '';

            // 处理缩写格式：取前两位大写，不足两位用O补齐
            $abbrCode = !empty($abbr)
                ? strtoupper(substr($abbr, 0, 2))
                : 'OF';
            $abbrCode = str_pad($abbrCode, 2, 'O', STR_PAD_RIGHT);
        } else {
            $abbrCode = 'OF';
        }

        // 3. 处理创建日期 (yyMMdd)
        $date = $createTime ?: date('Y-m-d H:i:s');
        $dateCode = date('ymd', strtotime($date));

        // 4. 获取当天订单序号 (事务内加锁确保唯一)
        $startTime = date('Y-m-d 00:00:00', strtotime($date));
        $endTime = date('Y-m-d 23:59:59', strtotime($date));


        $orderCount = Db::name('order')
            ->where('owner', $ownerId)
            ->where('create_time', '>=', $startTime)
            ->where('create_time', '<=', $endTime)
            ->count();
        if($abbrCode == 'OF'){
            $orderCount = Db::name('order')
                ->whereLike('order_no', "%{$abbrCode}{$dateCode}%")
                ->where('create_time', '>=', $startTime)
                ->where('create_time', '<=', $endTime)
                ->count();
        }

        $sequence = $orderCount + 1;

        // 序号格式化为两位数字
        $sequenceCode = str_pad($sequence, 2, '0', STR_PAD_LEFT);

        // 5. 拼接最终订单号
        return "{$prefix}{$abbrCode}{$dateCode}{$sequenceCode}";
    }

    /**
     * 添加操作日志
     * @param $userId
     * @param $businessName
     * @param $content
     * @return void
     */
    public static function storeLog($userId, $businessName, $content)
    {
        $request = new Request();
        // 获取当前日期
        $date = date('Y-m-d');
        $month = date('Y-m');
        $day = date('d');

        // 构建文件路径
        $baseDir = runtime_path() . 'logs/' . $businessName . '/' . $month . '/';
        $filePath = $baseDir . $day . '.log';

        // 创建目录
        if (!is_dir($baseDir)) {
            mkdir($baseDir, 0777, true);
        }

        // 构建日志内容
        $logContent = sprintf("[%s] User ID: %d, Content: %s\n", date('Y-m-d H:i:s'), $userId, $content);

        // 写入日志文件
        file_put_contents($filePath, $logContent, FILE_APPEND);
    }




}

